package com.hollysys.usersync.utils;

import org.springframework.lang.Nullable;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 字典生成 - 工具类
 *
 * @author Jeremy Yim
 * @date 2022-04-15
 */
public class MapUtil {

    public static <R, T> Map<R, T> list2map(List<T> dataList, Function<T, R> key, @Nullable Predicate<T> filter) {
        // 筛选分类
        filter = Objects.isNull(filter) ? u -> true : filter;
        return dataList.parallelStream().filter(filter).collect(Collectors.toMap(key, data -> data));
    }


    public static <K, V> Optional<List<V>> getValueByKey(List<K> values, Map<K, V> map) {
        if (values == null || values.isEmpty()) {
            return Optional.empty();
        }
        if (map == null || map.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(values.parallelStream()
                .map(map::get).filter(Objects::nonNull)
                .collect(Collectors.toList()));
    }
}
